package com.lzx.iteam.adapter;

import android.content.Context;
import android.graphics.BitmapFactory;
import android.media.Image;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.ImageSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import com.lzx.iteam.R;
import com.lzx.iteam.bean.MyTalkMessageData;
import com.lzx.iteam.emotion.gif.AnimatedGifDrawable;
import com.lzx.iteam.emotion.gif.AnimatedImageSpan;
import com.lzx.iteam.util.DateUtil;
import com.lzx.iteam.util.ImageLoaderInterface;
import com.lzx.iteam.util.StringUtil;
import com.lzx.iteam.widget.RoundImageView;
import io.rong.imageloader.core.ImageLoader;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by Megan on 15/10/15.
 */
public class MyTalkMessageAdapter extends BaseAdapter {

    private Context mContext;
    private ViewHolder holder = null;

    private ArrayList<MyTalkMessageData> talkMessageDatas;
    private ImageLoader mImageLoader;


    public MyTalkMessageAdapter(Context mContext) {
        this.mContext = mContext;
        mImageLoader = ImageLoader.getInstance();
    }

    public void bindData(ArrayList<MyTalkMessageData> talkMessageDatas) {
        this.talkMessageDatas = talkMessageDatas;
        notifyDataSetChanged();

    }


    @Override
    public int getCount() {
        return talkMessageDatas.size();
    }

    @Override
    public Object getItem(int position) {
        return talkMessageDatas.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup viewGroup) {
        MyTalkMessageData talkMessageData = talkMessageDatas.get(position);
        if (convertView == null) {
            holder = new ViewHolder();
            convertView = LayoutInflater.from(mContext).inflate(R.layout.my_talk_message_image_item, null);
            holder.userName = (TextView) convertView.findViewById(R.id.talk_message_item_user_name);
            holder.userTime = (TextView) convertView.findViewById(R.id.talk_message_item_user_time);
            holder.userComment = (TextView) convertView.findViewById(R.id.talk_message_item_comment);
            holder.userImage = (RoundImageView) convertView.findViewById(R.id.talk_message_item_user_img);
            holder.oriImage = (ImageView) convertView.findViewById(R.id.talk_message_item_image);
            holder.oriContent = (TextView) convertView.findViewById(R.id.talk_message_item_text);
            convertView.setTag(holder);

        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        mImageLoader.displayImage(talkMessageData.msgUImg, holder.userImage, ImageLoaderInterface.optionHeadImage);
        if (StringUtil.isEmpty(talkMessageData.talkThumb) || "null".equals(talkMessageData.talkThumb)) {
            holder.oriImage.setVisibility(View.GONE);
        } else {
            holder.oriImage.setVisibility(View.VISIBLE);
            mImageLoader.displayImage(talkMessageData.talkThumb, holder.oriImage, ImageLoaderInterface.optionEventImage);
        }
        holder.userName.setText(talkMessageData.msgUName);
        holder.userTime.setText(DateUtil.getChatTime(Long.parseLong(talkMessageData.msgCTime) * 1000));
        if ("1".equals(talkMessageData.msgType)) {
            holder.userComment.setText("赞了我");
        } else {
            if (!StringUtil.isEmpty(talkMessageData.msgComment)) {
                SpannableStringBuilder sb = handler(holder.userComment,
                        talkMessageData.msgComment);
                holder.userComment.setText(sb);
            }
        }
        if (!StringUtil.isEmpty(talkMessageData.text)) {
            SpannableStringBuilder content = handler(holder.oriContent,
                    talkMessageData.text);
            holder.oriContent.setText(content);
        }

        return convertView;
    }

    private class ViewHolder {
        TextView userName;
        TextView userComment;
        TextView userTime;
        RoundImageView userImage;
        ImageView oriImage;
        TextView oriContent;


    }

    private SpannableStringBuilder handler(final TextView gifTextView, String content) {
        SpannableStringBuilder sb = new SpannableStringBuilder(content);
        String regex = "(\\#\\[face/png/f_static_)\\d{3}(.png\\]\\#)";
        Pattern p = Pattern.compile(regex);
        Matcher m = p.matcher(content);
        while (m.find()) {
            String tempText = m.group();
            try {
                String num = tempText.substring("#[face/png/f_static_".length(), tempText.length() - ".png]#".length());
                String gif = "face/gif/f" + num + ".gif";
                /**
                 * 如果open这里不抛异常说明存在gif，则显示对应的gif
                 * 否则说明gif找不到，则显示png
                 * */
                InputStream is = mContext.getAssets().open(gif);
                sb.setSpan(new AnimatedImageSpan(new AnimatedGifDrawable(is, new AnimatedGifDrawable.UpdateListener() {
                            @Override
                            public void update() {
                                gifTextView.postInvalidate();
                            }
                        })), m.start(), m.end(),
                        Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                is.close();
            } catch (Exception e) {
                String png = tempText.substring("#[".length(), tempText.length() - "]#".length());
                try {
                    int resID = mContext.getResources().getIdentifier(png.split("/")[2].substring(0, png.split("/")[2].indexOf(".")), "drawable", mContext.getApplicationInfo().packageName);
                    sb.setSpan(new ImageSpan(mContext, BitmapFactory.decodeResource(mContext.getResources(), resID)), m.start(), m.end(),
                            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
//                    sb.setSpan(new ImageSpan(mContext, BitmapFactory.decodeStream(mContext.getAssets().open(png))), m.start(), m.end(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                } catch (Exception e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
//                e.printStackTrace();
            }
        }
        return sb;
    }


}
